"""
数据库日志处理器
"""
import asyncio
import json
from typing import Dict, Any, Optional
from datetime import datetime
from loguru import logger
from database.connection import db_manager
from database.repositories import SystemLogRepository


class DatabaseLogHandler:
    """数据库日志处理器"""
    
    def __init__(self):
        self._queue = asyncio.Queue()
        self._worker_task = None
        self._started = False
    
    async def start(self):
        """启动数据库日志处理器"""
        if not self._started:
            self._started = True
            self._worker_task = asyncio.create_task(self._worker())
            logger.info("数据库日志处理器已启动")
    
    async def stop(self):
        """停止数据库日志处理器"""
        if self._started:
            self._started = False
            if self._worker_task:
                self._worker_task.cancel()
                try:
                    await self._worker_task
                except asyncio.CancelledError:
                    pass
            logger.info("数据库日志处理器已停止")
    
    async def log(self, level: str, message: str, task_id: Optional[str] = None, 
                  extra_data: Optional[Dict[str, Any]] = None, show_in_ui: int = 1):
        """添加日志到队列"""
        log_data = {
            'level': level.upper(),
            'message': message,
            'task_id': task_id,
            'extra_data': extra_data or {},
            'show_in_ui': show_in_ui,
            'created_at': datetime.utcnow()
        }
        
        try:
            await self._queue.put(log_data)
        except Exception as e:
            logger.error(f"添加日志到队列失败: {e}")
    
    async def _worker(self):
        """工作线程，处理日志队列"""
        while self._started:
            try:
                # 等待日志数据，设置超时避免阻塞
                log_data = await asyncio.wait_for(self._queue.get(), timeout=1.0)
                
                # 获取数据库会话
                async with db_manager.get_session() as session:
                    log_repo = SystemLogRepository(session)
                    await log_repo.create(log_data)
                
                # 标记任务完成
                self._queue.task_done()
                
            except asyncio.TimeoutError:
                # 超时是正常的，继续循环
                continue
            except Exception as e:
                logger.error(f"处理数据库日志失败: {e}")
                # 如果队列中有任务，标记为完成以避免死锁
                try:
                    self._queue.task_done()
                except ValueError:
                    pass


# 全局数据库日志处理器实例
db_log_handler = DatabaseLogHandler()


def database_log_sink(record_json):
    print("数据库日志接收器被调用")
    """Loguru数据库日志接收器"""
    try:
        # 解析JSON格式的record
        import json
        record = json.loads(record_json)
     
        # 兼容loguru的标准record结构
        record_data = record.get("record", record)
        level = record_data.get("level", {}).get("name", "INFO")
        message = record_data.get("message", "")
        extra = record_data.get("extra", {})
        # 兼容extra嵌套结构

         # 合并extra和extra['extra']（如有）
        extra_data = {k: v for k, v in extra.items() if v is not None}
        if "extra" in extra and isinstance(extra["extra"], dict):
            extra_data.update({k: v for k, v in extra["extra"].items() if v is not None})
        show_in_ui = extra_data.get("show_in_ui", 0)
        task_id = extra.get("task_id")
        
        # 准备数据库数据
        log_data = {
            'level': level,
            'message': message,
            'task_id': task_id,
            'extra_data': extra,
            'show_in_ui': show_in_ui,
            
        }
        
     
        
        
     

        
        async def save_log():
            try:
                async for db_session in db_manager.get_session():
                    try:
                        log_repo = SystemLogRepository(db_session)
                        result = await log_repo.create(log_data)
                        break
                    except Exception as repo_e:
                        print(f"仓库操作失败: {repo_e}")
                        # 确保session被正确关闭
                        try:
                            await db_session.rollback()
                        except:
                            pass
                        raise
            except Exception as e:
                print(f"数据库保存失败: {e}")
        
        # 运行异步保存
        try:
            loop = asyncio.get_event_loop()
            if loop.is_running():
                # 创建任务但不等待（避免阻塞）
                task = asyncio.create_task(save_log())
                # 为了避免连接泄漏，添加一个简单的完成回调
                def task_done_callback(future):
                    if future.exception():
                        print(f"日志保存任务异常: {future.exception()}")
                task.add_done_callback(task_done_callback)
            else:
                asyncio.run(save_log())
        except RuntimeError:
            try:
                asyncio.run(save_log())
            except Exception as e:
                print(f"日志保存运行失败: {e}")
        
    except Exception as e:
        # 避免日志记录本身出错导致无限循环
        print(f"数据库日志记录失败: {e}")


async def init_database_logging():
    """初始化数据库日志记录"""
    await db_log_handler.start()
    return db_log_handler


async def shutdown_database_logging():
    """关闭数据库日志记录"""
    await db_log_handler.stop()
